package com.zixi.config;

import com.zixi.pojo.User;
import com.zixi.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm     extends AuthorizingRealm
//真正的权限操作
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权（一进入一些需要权限的页面就会执行此方法）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权doGetAuthoriZationInfo");
        //给用户授予权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

//        simpleAuthorizationInfo.addStringPermission("user:root");//无条件给所有人加上"user:root"则都有权限了

        /*
            条件授权:
                1.拿到当前对象
                2.设置当前用户的权限(数据库字段存着权限)

         */
        // 1.拿到当前对象
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        // 2.设置当前用户的权限(数据库字段存着权限字符串)
        simpleAuthorizationInfo.addStringPermission(currentUser.getPerms());


        return simpleAuthorizationInfo;//返回配置好的对象
    }


    //认证(一登录就会执行此方法)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthentiCationInfo");
        //在Contriller层写

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        //链接真实数据库
        User user = userService.queryUserByNsername(usernamePasswordToken.getUsername());

        if (user == null) {
            return null;//抛出异常 UnknownAccountException
        }

        //密码认证，shiro做,只需要给正确的密码即可
        //可以加密： MD5 MD5盐值加密
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
        //第一个属性放user 上面的授权就能拿到信息了
    }
}
